/*
 * MAX44009.c
 *
 *  Created on: Aug 28, 2020
 *      Author: daniel
 */

#include "MAX44009.h"

extern I2C_HandleTypeDef hi2c1;

#define MAX44009_I2C		hi2c1
#define MAX44009_ADDR		MAX44009_DEFAULT_ADDRESS

///////////////////////////////////////////////////////////
//
// PRIVATE
//
static bool max44009_read(uint8_t reg, uint8_t* value)
{
	return (HAL_I2C_Mem_Read(&MAX44009_I2C, MAX44009_ADDR<<1, reg, I2C_MEMADD_SIZE_8BIT, value, 1, 100) == HAL_OK);
}

static bool max44009_write(uint8_t reg, uint8_t value)
{
    uint8_t				buffer[2];
    buffer[0] = reg;
    buffer[1] = value;

	return (HAL_I2C_Master_Transmit(&MAX44009_I2C, MAX44009_ADDR<<1, buffer, 2, 100) == HAL_OK);

}



//float max44009_getLux(void)
bool max44009_getLux(float* lux)
{
	HAL_StatusTypeDef 	status = 0;
	uint8_t				d[2] = {0, 0};

	status = HAL_I2C_Mem_Read(&MAX44009_I2C, MAX44009_ADDR<<1, MAX44009_LUX_READING_HIGH, I2C_MEMADD_SIZE_8BIT, d, 2, 100);
	if (status != HAL_OK)
	{
		return false;
	}

	uint8_t e = d[0] >> 4;
	if (e == 0x0F)
	{
		*lux = 0;
		return true;
	}
	uint32_t m = ((d[0] & 0x0F) << 4) + (d[1] & 0x0F);
	m <<= e;
	*lux = m * 0.045;
	return true;
}

bool max44009_setConfiguration(const uint8_t value)
{
	return max44009_write(MAX44009_CONFIGURATION, value);
}

bool max44009_getConfiguration(uint8_t* config)
{
	return max44009_read(MAX44009_CONFIGURATION, config);
}

bool max44009_setAutomaticMode()
{
	// CDR & TIM cannot be written in automatic mode
	uint8_t config;
	if (!max44009_read(MAX44009_CONFIGURATION, &config)) {
		return false;
	}
	config &= ~MAX44009_CFG_MANUAL;
	return max44009_write(MAX44009_CONFIGURATION, config);
}

bool max44009_setContinuousMode()
{
	uint8_t config;
	if (!max44009_read(MAX44009_CONFIGURATION, &config)) {
		return false;
	}
	config |= MAX44009_CFG_CONTINUOUS;
	return max44009_write(MAX44009_CONFIGURATION, config);
}

bool max44009_clrContinuousMode()
{
	uint8_t config;
	if (!max44009_read(MAX44009_CONFIGURATION, &config)) {
		return false;
	}
	config &= ~MAX44009_CFG_CONTINUOUS;
	return max44009_write(MAX44009_CONFIGURATION, config);
}

bool max44009_setManualMode(uint8_t CDR, uint8_t TIM)
{
	if (CDR !=0) CDR = 1;
	if (TIM > 7) TIM = 7;
	uint8_t config;
	if (!max44009_read(MAX44009_CONFIGURATION, &config)) {
		return false;
	}
	config |= MAX44009_CFG_MANUAL;
	config &= 0xF0;                     // clear old CDR & TIM bits
	config |= CDR << 3 | TIM;           // set new CDR & TIM bits
	return max44009_write(MAX44009_CONFIGURATION, config);
}

